package com.iotechn.unimall.admin.api.purchaseWarehouseOrderGoods;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.domain.CategoryDO;
import com.iotechn.unimall.data.domain.PurchaseWarehouseOrderGoodsDO;
import com.iotechn.unimall.data.dto.warehouse.PurchaseWarehouseOrderGoodsDTO;
import com.iotechn.unimall.data.mapper.CategoryMapper;
import com.iotechn.unimall.data.mapper.PurchaseWarehouseOrderGoodsMapper;
import com.iotechn.unimall.data.model.Page;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class PurchaseWarehouseOrderGoodsServiceImpl implements PurchaseWarehouseOrderGoodsService {
    @Autowired
    private PurchaseWarehouseOrderGoodsMapper purchaseWarehouseOrderGoodsMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Page<PurchaseWarehouseOrderGoodsDO> list(Integer page, Integer limit, Long adminId) throws ServiceException {
        Wrapper<PurchaseWarehouseOrderGoodsDO> wrapper = new EntityWrapper<PurchaseWarehouseOrderGoodsDO>();
        /**if (!StringUtils.isEmpty(name)) {
         wrapper.like("username", name);
         }**/
        wrapper.orderBy("id", false);
        Integer count = purchaseWarehouseOrderGoodsMapper.selectCount(wrapper);
        List<PurchaseWarehouseOrderGoodsDO> PurchaseWarehouseOrderGoodsDOS = purchaseWarehouseOrderGoodsMapper.selectPage(new RowBounds((page - 1) * limit, limit), wrapper);
        return new Page<>(PurchaseWarehouseOrderGoodsDOS, page, limit, count);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PurchaseWarehouseOrderGoodsDO create(PurchaseWarehouseOrderGoodsDO purchaseWarehouseOrderGoodsDO, Long adminId) throws ServiceException {
//            purchaseWarehouseOrderGoodsDO.set(adminId);
        Date now = new Date();
        purchaseWarehouseOrderGoodsDO.setGmtCreate(now);
        purchaseWarehouseOrderGoodsDO.setGmtUpdate(now);
        if (purchaseWarehouseOrderGoodsMapper.insert(purchaseWarehouseOrderGoodsDO) > 0) {
            purchaseWarehouseOrderGoodsDO.setId(purchaseWarehouseOrderGoodsDO.getId());
            return purchaseWarehouseOrderGoodsDO;
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String update(PurchaseWarehouseOrderGoodsDO purchaseWarehouseOrderGoodsDO, Long adminId) throws ServiceException {
        Long id = purchaseWarehouseOrderGoodsDO.getId();
        if (id == null) {
            return "fail";
        }
        Date now = new Date();
        purchaseWarehouseOrderGoodsDO.setGmtUpdate(now);
        if (purchaseWarehouseOrderGoodsMapper.updateById(purchaseWarehouseOrderGoodsDO) > 0) {
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String delete(Long id, Long adminId) throws ServiceException {
        if (purchaseWarehouseOrderGoodsMapper.deleteById(id) > 0) {
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);

    }

    @Override
    public PurchaseWarehouseOrderGoodsDO detail(Long id, Long adminId) throws ServiceException {
        return purchaseWarehouseOrderGoodsMapper.selectById(id);
    }

    @Override
    public Page querySkusByWarehouseId(Integer page, Integer limit, Long warehouseId, String skuIds, String search) {
        LinkedList<Long> childrenIds = new LinkedList<>();
        if (skuIds != null && !"".equals(skuIds)) {
            List<CategoryDO> childrenList = categoryMapper.selectList(new EntityWrapper<CategoryDO>().eq("parent_id", skuIds));
            // 传入类目拥有的三级类目集合
            // 传入类目没有子类目
            if (CollectionUtils.isEmpty(childrenList)) {
                // 则传入类目为三级类目
                childrenIds.add(Long.valueOf(skuIds));
            } else {
                CategoryDO categoryDO = categoryMapper.selectById(skuIds);
                // 检验传入类目是一级还是二级类目
                if (categoryDO.getParentId() != 0L) {
                    //二级分类
                    childrenList.forEach(item -> {
                        childrenIds.add(item.getId());
                    });
                } else {
                    //一级分类
                    childrenList.forEach(item -> {
                        List<CategoryDO> leafList = categoryMapper.selectList(new EntityWrapper<CategoryDO>().eq("parent_id", item.getId()));
                        if (!CollectionUtils.isEmpty(leafList)) {
                            leafList.forEach(leafItem -> {
                                childrenIds.add(leafItem.getId());
                            });
                        }
                    });
                }
            }

        }
        Integer start = (page - 1) * limit;
        Integer end = limit;
        List<PurchaseWarehouseOrderGoodsDTO> purchaseWarehouseOrderGoodsDTOS = purchaseWarehouseOrderGoodsMapper.querySkusByWarehouseId(warehouseId, childrenIds, start, end, search);
        Integer count = purchaseWarehouseOrderGoodsMapper.countSkusByWarehouseId(warehouseId, childrenIds, search);
        return new Page<>(purchaseWarehouseOrderGoodsDTOS, page, limit, count);
    }

    @Override
    public List<Map<String, Object>> listWarehouseSkusByPara(Long warehouseOrderId, Long warehouseId) throws ServiceException {
        List<Map<String, Object>> result = purchaseWarehouseOrderGoodsMapper.selectMaps(new EntityWrapper<PurchaseWarehouseOrderGoodsDO>()
                .eq(warehouseOrderId != null, "warehouse_order_id", warehouseOrderId)
                .eq(warehouseId != null, "warehouse_id", warehouseId)
                .setSqlSelect("warehouse_goods_buy_num as warehouseGoodsBuyNum", "warehouse_goods_price as warehouseGoodsPrice", "goods_name as goodsName", "goods_bar_code as barCode", "goods_img as img", "goods_id as goodsId",
                        "goods_unit as unit", "warehouse_goods_amount as warehouseGoodsAmount",
                        "goods_id as spuId", "spu_name as spuName", "sku_id as skuId", "sku_name as skuName", "goods_aver_price as goodsAverPrice"));
        //处理价格
        result.stream().map(i -> {

            Float originalGoodPrice = Float.valueOf(String.valueOf(i.get("warehouseGoodsPrice")));
            i.put("warehouseGoodsPrice", originalGoodPrice / 100);
            Float averPrice = Float.valueOf(String.valueOf(i.get("goodsAverPrice")));
            i.put("goodsAverPrice", averPrice / 100);
            Float warehouseGoodsAmount = Float.valueOf(String.valueOf(i.get("warehouseGoodsAmount")));
            i.put("warehouseGoodsAmount", warehouseGoodsAmount / 100);
            return i;
        }).collect(Collectors.toList());
        return result;

    }


}